package com.dabai.applicationmanager.ui.smallprogram;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.DhcpInfo;
import android.net.Uri;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dabai.applicationmanager.R;
import com.dabai.applicationmanager.adapter.AppAdapter;
import com.dabai.applicationmanager.bean.AppBaseInfo;
import com.dabai.applicationmanager.databinding.ActivityFileTransferBinding;
import com.dabai.applicationmanager.dialog.MdcDialog;
import com.dabai.applicationmanager.dialog.TipAlertDialog;
import com.dabai.applicationmanager.sort.AppByLastUpdate;
import com.dabai.applicationmanager.sort.AppByName;
import com.dabai.applicationmanager.sort.AppBySize;
import com.dabai.applicationmanager.sort.AppByTargetApi;
import com.dabai.applicationmanager.utils.OtherUtils;
import com.dabai.applicationmanager.utils.WifiAdmin;
import com.dabai.dbutils.qrcode.QRCodeUtils;
import com.dabai.dbutils.toast.DBToast;
import com.dabai.dbutils.utils.AppUtils;
import com.dabai.dbutils.utils.DabaiUtils;
import com.dabai.dbutils.utils.DateUtils;
import com.dabai.dbutils.utils.FileUtils;
import com.dabai.dbutils.utils.NotificationUtils;
import com.dabai.dbutils.utils.SharedPreferencesBasicUse;
import com.dabai.dbutils.utils.SharedPreferencesUtils;
import com.dabai.dbutils.utils.ZipUtils;
import com.dabai.dbutils.utils.component.ActivityUtils;
import com.dabai.uitools.base.BaseAppCompatActivity;
import com.dabai.uitools.utils.ViewUtils;
import com.github.promeg.pinyinhelper.Pinyin;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.permissionx.guolindev.PermissionX;

import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.exception.ZipException;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

import me.zhanghai.android.appiconloader.AppIconLoader;
import me.zhanghai.android.fastscroll.FastScrollerBuilder;

public class FileTransferActivity extends BaseAppCompatActivity {

    Context context;

    private WifiManager mWifiManager;

    private AppAdapter appAdapter;
    private ArrayList<AppBaseInfo> appBaseInfo;
    private List<PackageInfo> packageInfos;

    ActivityFileTransferBinding aft;
    private File receiveDir;
    private AlertDialog qrDia;


    @SuppressLint("MissingPermission")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        aft = ActivityFileTransferBinding.inflate(getLayoutInflater());
        setContentView(aft.getRoot());

        context = this;

        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            DBToast.showText(context, "本功能只支持Android 8.1及以上版本!");
            finish();
        }

        TipAlertDialog.init(context);

        aft.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        aft.recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayout.VERTICAL));

        aft.swipeRefreshLayout.setOnRefreshListener(this::refreshList);
        aft.swipeRefreshLayout.setColorSchemeColors(getColor(R.color.teal_700));

        new FastScrollerBuilder(aft.recyclerView).setPopupStyle(textView -> {
            textView.setBackgroundColor(getResources().getColor(R.color.teal_700));
            textView.setTextColor(Color.WHITE);
            textView.setTextSize(16f);
            textView.setPadding(30,30,200,30);
        }).build();

        refreshList();

        SharedPreferencesBasicUse.init(context);

        PermissionX.init(FileTransferActivity.this)
                .permissions(Manifest.permission.CHANGE_WIFI_STATE, Manifest.permission.ACCESS_FINE_LOCATION)
                .request((allGranted, grantedList, deniedList) -> {
                    if (!allGranted) {
                        DBToast.showText(context, "无WiFi权限，不能使用此功能。", false);
                        finish();
                    } else {

                        initWifi();

                    }
                });

        aft.imageButton.setOnClickListener(v -> {

            if (appAdapter.getCheckData().size() <= 0) {
                DBToast.showText(context, "未选中任何软件包!", false);
                return;
            }


            if (mWifiManager.isWifiEnabled()) {
                new MaterialAlertDialogBuilder(context, R.style.DBTheme_Dialog_RoundTheme)
                        .setTitle("选择传输网络")
                        .setItems(new CharSequence[]{"继续使用当前局域网", "新建临时热点"}, (dialog, which) -> {
                            if (which == 0) {
                                QRCodeUtils.startQrCodeScanner(this, 501);
                            } else if (which == 1) {
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                                    startLocalOnlyHotspot();
                                } else {
                                    DabaiUtils.showDialog(context, "当前系统不支持临时热点,请手动开启热点,并引导接收端连接!").getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);
                                }
                            }
                        })
                        .show().getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);
            } else if (isWifiApOpen(context)) {
                QRCodeUtils.startQrCodeScanner(this, 501);
            } else {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    startLocalOnlyHotspot();
                } else {
                    DabaiUtils.showDialog(context, "当前系统不支持临时热点,请手动开启热点,并引导接收端连接!").getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);
                }
            }

        });

    }


    /**
     * 检测无线ap开启
     *
     * @param context 上下文
     * @return boolean
     */
    public static boolean isWifiApOpen(Context context) {
        try {
            WifiManager manager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            //通过放射获取 getWifiApState()方法
            Method method = manager.getClass().getDeclaredMethod("getWifiApState");
            //调用getWifiApState() ，获取返回值
            int state = (int) method.invoke(manager);
            //通过放射获取 WIFI_AP的开启状态属性
            Field field = manager.getClass().getDeclaredField("WIFI_AP_STATE_ENABLED");
            //获取属性值
            int value = (int) field.get(manager);
            //判断是否开启
            return state == value;
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | NoSuchFieldException e) {
            e.printStackTrace();
        }
        return false;
    }


    @SuppressLint("MissingPermission")
    @RequiresApi(api = Build.VERSION_CODES.O)
    public void startLocalOnlyHotspot() {

        TipAlertDialog.getInstance(context).showTipLayout("正在启动热点...");

        mWifiManager.startLocalOnlyHotspot(new WifiManager.LocalOnlyHotspotCallback() {

            @TargetApi(Build.VERSION_CODES.O)
            @Override
            public void onStarted(WifiManager.LocalOnlyHotspotReservation reservation) {
                super.onStarted(reservation);
                WifiConfiguration wifiConfiguration = reservation.getWifiConfiguration();

                TipAlertDialog.getInstance(context).hideTipLayout();

                String qr = "WIFI:T:WPA;P:" + wifiConfiguration.preSharedKey + ";S:" + wifiConfiguration.SSID + ";";

                ImageView imageView = new ImageView(context);
                imageView.setPadding(10,10,10,10);
                imageView.setImageBitmap(QRCodeUtils.createSimpleQrCodeBitmap(qr));

                new MaterialAlertDialogBuilder(context,R.style.DBTheme_Dialog_RoundTheme)
                        .setTitle("请接收端扫码连接此临时热点")
                        .setView(imageView)
                        .setCancelable(false)
                        .setPositiveButton("扫码传输", (dialog, which) -> QRCodeUtils.startQrCodeScanner(FileTransferActivity.this, 501))
                        .setNeutralButton("取消传输", (dialog, which) -> reservation.close())
                        .show().getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);

            }

            @Override
            public void onStopped() {
                super.onStopped();
                TipAlertDialog.getInstance(context).hideTipLayout();
                DBToast.showText(context, "热点已经关闭!", false);
            }

            @Override
            public void onFailed(int reason) {
                super.onFailed(reason);
                TipAlertDialog.getInstance(context).hideTipLayout();
                DBToast.showText(context, "热点启动失败!", false);
            }
        }, new Handler());
    }


    @SuppressLint("SetTextI18n")
    public void refreshList() {
        aft.swipeRefreshLayout.setRefreshing(false);

        int mode;

        if (SharedPreferencesUtils.getDefaultSharedPreferences(context).getBoolean("revealAllApplication", false)) {
            mode = 0;
        } else {
            mode = 1;
        }

        new Thread(() -> {

            switch (mode) {
                case 0:
                    runOnUiThread(() -> TipAlertDialog.getInstance(context).showTipLayout("正在加载全部应用"));
                    packageInfos = AppUtils.getAllInstalledPackages(context);
                    break;
                case 1:
                    runOnUiThread(() -> TipAlertDialog.getInstance(context).showTipLayout("正在加载用户应用列表"));
                    packageInfos = AppUtils.getUserInstalledPackages(context);
                    break;
            }

            appBaseInfo = new ArrayList<>();

            AppIconLoader appIconLoader = new AppIconLoader(130, true, context);
            PackageManager packageManager = this.getPackageManager();

            for (PackageInfo packageInfo : packageInfos) {

                ApplicationInfo applicationInfo = packageInfo.applicationInfo;
                String appName = packageManager.getApplicationLabel(applicationInfo).toString();

                AppBaseInfo appInfo = new AppBaseInfo();

                appInfo.setName(appName);
                appInfo.setPackageName(packageInfo.packageName);
                appInfo.setVersion(packageInfo.versionName);
                appInfo.setVersionCode(packageInfo.versionCode + "");
                appInfo.setPath(packageInfo.applicationInfo.publicSourceDir);

                switch (OtherUtils.getSortWay(context)) {
                    case 2:
                        appInfo.setLastUpdate(packageInfo.lastUpdateTime);
                        break;
                    case 4:
                        appInfo.setTargetApi(packageInfo.applicationInfo.targetSdkVersion);
                        break;
                }
                appInfo.setSize(new File(packageInfo.applicationInfo.publicSourceDir).length());
                appInfo.setNameSort(Pinyin.toPinyin(appName.charAt(0)).toUpperCase());


                if (AppUtils.isFreeze(context, packageInfo.packageName)) {
                    appInfo.setFreeze(true);
                }

                try {
                    appInfo.setIcon(appIconLoader.loadIcon(packageInfo.applicationInfo));
                } catch (Exception e) {
                    appInfo.setIcon(ViewUtils.drawableToBitmap(packageManager.getApplicationIcon(applicationInfo)));
                }

                appBaseInfo.add(appInfo);
            }


            switch (OtherUtils.getSortWay(context)) {
                case 1:
                    Collections.sort(appBaseInfo,new AppByName(true));
                    break;
                case 2:
                    Collections.sort(appBaseInfo,new AppByLastUpdate(false));
                    break;
                case 3:
                    Collections.sort(appBaseInfo,new AppBySize(false));
                    break;
                case 4:
                    Collections.sort(appBaseInfo,new AppByTargetApi(false));
                    break;
            }

            appAdapter = new AppAdapter(appBaseInfo);
            appAdapter.setAnimationWithDefault(BaseQuickAdapter.AnimationType.AlphaIn);


            runOnUiThread(() -> {
                aft.recyclerView.setAdapter(appAdapter);

                setTitle("软件包互传(" + appAdapter.getData().size() + ")");
                TipAlertDialog.getInstance(context).hideTipLayout();


                appAdapter.setSelect(true);
                appAdapter.showAllCheckBox();

                aft.textView1.setText("已经选择" + appAdapter.getCheckData().size() + "项");

            });

            // 设置点击事件
            appAdapter.setOnItemClickListener((adapter, view, position) -> {

                //多选模式 , 拦截 之前的单击事件
                if (appAdapter.isSelect()) {
                    CheckBox checkBox = (CheckBox) adapter.getViewByPosition(position, R.id.checkBox);

                    if (checkBox != null) {
                        if (!checkBox.isChecked()) {
                            checkBox.setChecked(true);
                            appAdapter.setCheckData(position, true);

                        } else {
                            checkBox.setChecked(false);
                            appAdapter.setCheckData(position, false);
                        }

                        aft.textView1.setText("已经选择" + appAdapter.getCheckData().size() + "项");
                    }

                }

            });

        }).start();

    }


    private void initWifi() {
        //获取wifi管理类
        mWifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        //打开wifi
        if (mWifiManager != null) {
            mWifiManager.setWifiEnabled(true);
        }
    }


    // 获得主机地址
    private String getIp() {
        WifiManager wifiManager = (WifiManager) getApplicationContext()
                .getSystemService(Context.WIFI_SERVICE);
        DhcpInfo info = wifiManager.getDhcpInfo();
        return intToIp(info.serverAddress);
    }

    //ip格式化
    private String intToIp(int i) {
        return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF)
                + "." + ((i >> 24) & 0xFF);
    }

    //服务器通到打开

    ServerSocket server;
    Socket socketReceive;

    public void receiveFile(int port) {

        DBToast.showYellowToast(context, "已经开始监听接收端口...");

        new Thread(() -> {

            try {
                server = new ServerSocket(port);
                socketReceive = server.accept();

                runOnUiThread(() -> {
                    if (qrDia.isShowing()) {
                        qrDia.dismiss();
                    }

                    try {
                        TipAlertDialog.getInstance(context).showTipLayout("正在接收来自 " + socketReceive.getInetAddress().getHostAddress() + " 的文件...");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                });

                DataInputStream dis = new DataInputStream(socketReceive.getInputStream());
                // 文件名和长度
                String fileName = dis.readUTF();
                long fileLength = dis.readLong();

                File file = new File(OtherUtils.getTmpDirectory(context), fileName);

                FileOutputStream fos = new FileOutputStream(file);

                byte[] bytes = new byte[1024];
                int length;

                long count = 0;

                while ((length = dis.read(bytes, 0, bytes.length)) != -1) {
                    fos.write(bytes, 0, length);
                    fos.flush();

                    count += length;
                    long finalCount = count;

                    runOnUiThread(() -> TipAlertDialog.getInstance(context)
                            .showTipLayout("正在接收来自 " + socketReceive.getInetAddress().getHostAddress() + " 的文件\n("
                                    + (int) (((float) finalCount / (float) fileLength) * 100)
                                    + "%)"));

                    if (finalCount == fileLength) {
                        break;
                    }
                }

                dis.close();
                fos.close();
                socketReceive.close();
                server.close();

                runOnUiThread(() -> {

                    TipAlertDialog.getInstance(context).showTipLayout("正在解压...");

                    new Thread(() -> {

                        try {
                            File tagZipFile = new File(OtherUtils.getTmpDirectory(context), DateUtils.getNowTime("tmp.zip"));
                            ZipUtils.UnZipFolder(file.getAbsolutePath(), tagZipFile.getAbsolutePath());

                            File tagZipFile2 = new File(tagZipFile, "cache");
                            receiveDir = new File(OtherUtils.getReceiveFileDirectory(context), DateUtils.getNowTime("yyyy年MM月dd日HH时mm分ss秒接收的文件"));

                            FileUtils.copyDir(tagZipFile2.getAbsolutePath()
                                    , receiveDir.getAbsolutePath()
                                    , true);

                        } catch (Exception e) {

                            server = null;
                            socketReceive = null;

                            runOnUiThread(() -> {

                                FileUtils.delete(OtherUtils.getTmpDirectory(context));
                                NotificationUtils.notificationText(context, "receive_file", "文件互传进度", R.drawable.ic_outline_wifi_tethering_24
                                        , "接收失败", "解压失败!");

                                TipAlertDialog.getInstance(context).hideTipLayout();
                            });
                        }

                        runOnUiThread(() -> {
                            FileUtils.delete(OtherUtils.getTmpDirectory(context));

                            try {
                                OtherUtils.showDialog(context, "接收成功!").getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);

                                NotificationUtils.notificationText(context, "receive_file", "文件互传进度", R.drawable.ic_outline_wifi_tethering_24
                                        , "接收完成", "存放到" + receiveDir.getParent());

                                TipAlertDialog.getInstance(context).hideTipLayout();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                            server = null;
                            socketReceive = null;

                        });
                    }).start();


                });

            } catch (IOException e) {
                FileUtils.delete(OtherUtils.getTmpDirectory(context));
                Log.d("DBTAG", "receiveFile: " + e);
                e.printStackTrace();
                runOnUiThread(() -> {
                    DBToast.showText(context, "接收失败!", false);
                    NotificationUtils.notificationText(context, "receive_file", "文件互传进度", R.drawable.ic_outline_wifi_tethering_24
                            , "接收失败", "程序异常!");
                });
            }

        }).start();

    }


    @SuppressLint("MissingPermission")
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        if (itemId == android.R.id.home) {
            finish();
            return true;
        }
        else if (itemId == R.id.receiveFiles) {
            ActivityUtils.startActivity(context,ReceiveFileActivity.class);
        }
        else if (itemId == R.id.enableReceive) {


            if (mWifiManager.isWifiEnabled()) {

                if (socketReceive == null && server == null) {

                    String qr = "amf2f://af/?model=" + Build.MODEL.replaceAll(" ", "")
                            + "&mode=wifi"
                            + "&ip=" + intToIp(mWifiManager.getDhcpInfo().ipAddress)
                            + "&port=8866"
                            + "&ssid=" + mWifiManager.getConnectionInfo().getSSID()
                            + "&pass=";

                    ImageView imageView = new ImageView(context);
                   // imageView.setPadding(10,10,10,10);
                    imageView.setImageBitmap(QRCodeUtils.createSimpleQrCodeBitmap(qr));

                    qrDia= new MaterialAlertDialogBuilder(context,R.style.DBTheme_Dialog_RoundTheme)
                            .setTitle("请发送端扫描二维码")
                            .setView(imageView)
                            .setCancelable(false)
                            .setNeutralButton("取消传输", (dialog, which) -> finish()).create();

                    receiveFile(8866);

                }

                qrDia.getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);
                qrDia.show();

                return true;
            } else {

                new MaterialAlertDialogBuilder(context, R.style.DBTheme_Dialog_RoundTheme)
                        .setTitle("提示")
                        .setMessage("请和发送端连接至同一局域网,再点击此按钮!\n\n" +
                                "小提示:可以连接至发送端开启的WiFi热点,双方不需要开启数据流量!")
                        .setNeutralButton("取消", null)
                        .setPositiveButton("扫码连接", (dialog, which) -> QRCodeUtils.startQrCodeScanner(this, 601)).show().getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);


            }

            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        TipAlertDialog.destroyTipLayout();

        if (server != null) {
            try {
                server.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (socketReceive != null) {
            try {
                socketReceive.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        server = null;
        socketReceive = null;

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.receive, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 501) {
                if (data != null) {

                    try {
                        String wifiInfo = QRCodeUtils.getQrCodeScannerResult(data);

                        Uri mUri = Uri.parse(wifiInfo);

                        if (mUri.getQueryParameter("mode").equals("wifi")) {

                            MdcDialog.showConfirmDialog(context, "提示"
                                    , "确定发送 " + appAdapter.getCheckDataSize() + " 个软件包到 " +
                                            mUri.getQueryParameter("model") + " 设备嘛?"
                                    , new MdcDialog.OnConfirmDialogButtonListener() {
                                        @Override
                                        public void confirm() {

                                            extractFile(mUri.getQueryParameter("ip"),
                                                    Integer.parseInt(mUri.getQueryParameter("port")));

                                        }

                                        @Override
                                        public void cancel() {

                                        }
                                    });

                        }

                    } catch (Exception e) {
                        OtherUtils.showDialog(context, "请正确扫描接收端二维码!");
                    }

                }
            }


            if (requestCode == 601) {
                if (data != null) {
                    String wifiInfo = QRCodeUtils.getQrCodeScannerResult(data);
                    try {
                        linkWifiQr(wifiInfo);
                    } catch (Exception e) {
                        DBToast.showText(context,"请检查WiFi连接码是否合法!",false);
                    }
                }
            }
        }

    }


    /**
     * 链接wifi qr
     *
     * @param scanResult 扫描结果
     */
    public void linkWifiQr(String scanResult) throws Exception{

        String passwordTemp = scanResult.substring(scanResult
                .indexOf("P:"));
        String password = passwordTemp.substring(2,
                passwordTemp.indexOf(";"));
        String netWorkTypeTemp = scanResult.substring(scanResult
                .indexOf("T:"));
        String netWorkType = netWorkTypeTemp.substring(2,
                netWorkTypeTemp.indexOf(";"));
        String netWorkNameTemp = scanResult.substring(scanResult
                .indexOf("S:"));
        String netWorkName = netWorkNameTemp.substring(2,
                netWorkNameTemp.indexOf(";"));

        MdcDialog.showConfirmDialog(context, "提示",
                "确定连接到 [" + netWorkName + "] 嘛?\n\nWiFi名称:" + netWorkName + "\n密码:" + (password.equals("") ? "无密码" : password) + "\n加密方式:" + (netWorkType.equals("") ? "无" : netWorkType), new MdcDialog.OnConfirmDialogButtonListener() {
                    @Override
                    public void confirm() {

                        DBToast.showYellowToast(context,"正在尝试连接...");
                        WifiAdmin wifiAdmin = new WifiAdmin(getApplicationContext());

                        new Thread(() -> {

                            if (!wifiAdmin.mWifiManager.isWifiEnabled()) {
                                wifiAdmin.openWifi();
                            }

                            int net_type;
                            if (netWorkType
                                    .compareToIgnoreCase("wpa") == 0) {
                                net_type = WifiAdmin.TYPE_WPA;// wpa
                            } else if (netWorkType
                                    .compareToIgnoreCase("wep") == 0) {
                                net_type = WifiAdmin.TYPE_WEP;// wep
                            } else {
                                net_type = WifiAdmin.TYPE_NO_PASSWD;// 无加密
                            }

                            wifiAdmin.addNetwork(netWorkName, password, net_type);

                        }).start();

                    }
                    @Override
                    public void cancel() {

                    }
                }).getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);

    }


    private ArrayList<AppBaseInfo> appBaseInflows;

    /**
     * 提取文件
     *
     * @param ip   知识产权
     * @param port 港口
     */
    public void extractFile(String ip, int port) {

        TipAlertDialog.getInstance(context).showTipLayout("正在准备文件...");

        FileUtils.delete(OtherUtils.getTmpDirectory(context));

        ArrayList<File> shareList = new ArrayList<>();
        appBaseInflows = appAdapter.getCheckAppInflows();

        new Thread(() -> {

            for (int i = 0; i < appBaseInflows.size(); i++) {

                AppBaseInfo appBaseInfo = appBaseInflows.get(i);

                File soc = new File(appBaseInfo.getPath());
                File tag = new File(OtherUtils.getTmpDirectory(context), getFileNameRule(appBaseInfo) + ".apk");

                boolean isOk;
                if (
                        SharedPreferencesUtils.getDefaultSharedPreferences(context).getBoolean("skipAlreadyExist", true)
                                && tag.exists()) {
                    isOk = true;
                } else {
                    isOk = FileUtils.copyFile(soc, tag, true);
                }

                if (!isOk) {
                    runOnUiThread(() -> DBToast.showText(context, appBaseInfo.getName() + " 提取失败!", false));
                } else {
                    shareList.add(tag);
                }

            }

            File tagFile = new File(OtherUtils.getTmpDirectory(context), ip.replaceAll("\\.", "") + "_" + DateUtils.getNowTime(3) + ".zip");
            try {
                new ZipFile(tagFile).addFolder(OtherUtils.getTmpDirectory(context));
            } catch (ZipException e) {
                e.printStackTrace();
            }

            runOnUiThread(() -> {
                TipAlertDialog.getInstance(context).showTipLayout("正在发送...");
                sendFile(ip, port, tagFile);
            });

        }).start();

    }

    /**
     * 发送文件
     *
     * @param ip   知识产权
     * @param port 港口
     * @param file 文件
     */
    public void sendFile(String ip, int port, File file) {

        new Thread(() -> {

            try {
                Socket client = new Socket(ip, port);

                FileInputStream fis = new FileInputStream(file);
                //BufferedInputStream bi=new BufferedInputStream(new InputStreamReader(new FileInputStream(file),"GBK"));
                DataOutputStream dos = new DataOutputStream(client.getOutputStream());//client.getOutputStream()返回此套接字的输出流
                //文件名、大小等属性
                dos.writeUTF(file.getName());
                dos.flush();
                dos.writeLong(file.length());
                dos.flush();
                // 开始传输文件
                System.out.println("======== 开始传输文件 ========");
                byte[] bytes = new byte[1024];
                int length;

                long count = 0;

                while ((length = fis.read(bytes, 0, bytes.length)) != -1) {
                    dos.write(bytes, 0, length);
                    dos.flush();
                    count += length;
                    long finalCount = count;
                    runOnUiThread(() -> TipAlertDialog.getInstance(context).showTipLayout("正在发送到" + ip + "\n("
                            + (int) (((float) finalCount / (float) file.length()) * 100)
                            + "%)"));
                }
                System.out.println("======== 文件传输成功 ========");

                runOnUiThread(() -> {
                    NotificationUtils.notificationText(context, "receive_file", "文件互传进度", R.drawable.ic_outline_wifi_tethering_24
                            , "发送成功", "文件已经发送完成!");
                    OtherUtils.showDialog(context, "发送成功!").getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);
                    TipAlertDialog.getInstance(context).hideTipLayout();
                    FileUtils.delete(OtherUtils.getTmpDirectory(context));
                });

            } catch (IOException e) {
                FileUtils.delete(OtherUtils.getTmpDirectory(context));
                Log.d("DBTAG", "发送失败: " + e.getMessage());
                runOnUiThread(() -> {
                    OtherUtils.showDialog(context, "发送失败!" + e.getMessage()).getWindow().setWindowAnimations(com.dabai.uitools.R.style.DBAnim_Transitions_Via);
                    TipAlertDialog.getInstance(context).hideTipLayout();
                });
            }

        }).start();

    }


    /**
     * 获得文件名规则
     *
     * @param appBaseInfo 应用基本信息
     * @return {@link String}
     */
    public String getFileNameRule(AppBaseInfo appBaseInfo) {

        String rule = SharedPreferencesBasicUse.getString("extractNamingRules", "&n_&vn_&vc");

        try {
            PackageInfo packageInfo = getPackageManager().getPackageInfo(
                    appBaseInfo.getPackageName(), 0);
            ApplicationInfo applicationInfo = packageInfo.applicationInfo;

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                rule = rule
                        //minSdkVersion
                        .replaceAll("&msv", applicationInfo.minSdkVersion + "");
            }
            rule = rule
                    //targetSdkVersion
                    .replaceAll("&tsv", applicationInfo.targetSdkVersion + "")
                    //uid
                    .replaceAll("&uid", applicationInfo.uid + "");

        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return rule
                //应用名
                .replaceAll("&n", appBaseInfo.getName())
                //版本名
                .replaceAll("&vn", appBaseInfo.getVersion())
                //版本代码
                .replaceAll("&vc", appBaseInfo.getVersionCode())
                //包名
                .replaceAll("&pn", appBaseInfo.getPackageName());
    }


}